'use strict';
/* 
 * jshint indent: 2 
 * 
 * createdAt 2016-12-19 
 * by 小贝
 *
 *
 * 短信验证模块，
 */

var crypto = require('crypto');

var mysql = require('mysql');
var Sequelize = require('sequelize');
var AV        = require('leanengine');

var TopClient = require('../top_api/topClient').TopClient;

var Sms= require('../sqlmodels/smscode');
var ErrorCode = require('./err.js');
var ComSet = require('../comset');
var DataTypes = Sequelize;
const SMSClient = require('@alicloud/sms-sdk')
const accessKeyId = ComSet.client.appkey;
const secretAccessKey = ComSet.client.appsecret;
//初始化sms_client
var smsClient = new SMSClient({accessKeyId, secretAccessKey})

var sequelize = Sms.sequelize;

//发送验证码
function sendPasswordVcode(params,callback){
	params = params || {};
	if(!params){
	return  callback(ErrorCode.noParams,null);
	}
	else{
		let mobile = params.mobile;
		let randomNum = MathRand();
		//发送短信
	smsClient.sendSMS({
	    PhoneNumbers: mobile,
	    SignName: '来鱼',
	    TemplateCode: 'SMS_104650009',
	    TemplateParam: '{"code":'+randomNum+',"product":"来鱼验证码"}'
	}).then(function (res) {
	    let {Code}=res
	    if (Code === 'OK') {
	        var data = {
	            code : randomNum.toString(),
	            mobilenumber: mobile.toString()
	        }
	        Sms.create(data).then(function(result){
	          	return callback(ErrorCode.true);
	        })
	    }else{
	    	return callback(ErrorCode.SmsError);
	    }
	}, function (err) {
	    return callback(err);
	})
  	}
}

//验证完删除
function delSms(params,callback){
	  Sms.destroy({
	    where:{
	      mobilenumber:params.mobilenumber,
	      code:params.code
	    }
	  }).then(function(){
	    return callback(ErrorCode.true);
	  })
}


//查询验证码是否正确
function checkVcode(params,callback){
	params = params || {};
	if(!params){
		return  callback(ErrorCode.noParams,null);
	}
	else{
		var key = params.key;
		var text= params.text;
		sequelize.query('SELECT COUNT(*) FROM `smscode` WHERE `mobilenumber` =  $1 AND `code`= $2',
			{bind: [key,text], type: sequelize.QueryTypes.SELECT }
		).then(function(result){
			var count = result[0]['COUNT(*)'];
			if(count != 0){
				var data = {
				      mobilenumber:key,
				      code:text
				}
				delSms(data,function(){});
				return callback('1');
			}
			else{
				return callback('0');
			}
		},function(err){
			console.log(err);
		})
	}
}

//发送验证码
function sendVcode(params,callback){
	console.log(params)
	params = params || {};
	if(!params){
		return  callback(ErrorCode.noParams,null);
	}
	else{
	var mobile = params.mobile;
	var randomNum = MathRand();
	//发送短信
	smsClient.sendSMS({
	    PhoneNumbers: mobile,
	    SignName: '来鱼',
	    TemplateCode: 'SMS_104650009',
	    TemplateParam: '{"code":'+randomNum+',"product":"来鱼验证码"}'
	}).then(function (res) {
		console.log(res)
	    let {Code}=res;
	    if (Code === 'OK') {
	        var data = {
        		code : randomNum,
        		mobilenumber: mobile
        	}
        	Sms.create(data).then(function(result){
        		return callback(ErrorCode.true);
        	},function(err){
        		console.log(err);
        	})
	    }else{
	    	return callback(ErrorCode.SmsError);
	    }
	}, function (err) {
		console.log(err);
	    return callback(err);
	})
	}
}

function MathRand() {
    var Num = "";
    for (var i = 0; i < 6; i++) {
        Num += Math.floor(Math.random() * 10);
    }
    return Num;
}
module.exports.delSms = delSms;
module.exports.checkVcode = checkVcode;
module.exports.sendVcode  = sendVcode;
module.exports.sequelize = sequelize;
module.exports.sendPasswordVcode = sendPasswordVcode;